#pragma once

#include <iostream>
#include <pthread.h>

//线程互斥
namespace MutexModule
{
    class Mutex
    {
    public:
        //锁不允许拷贝和赋值，要保证用到的是同一个锁
        Mutex(const Mutex &) = delete;
        const Mutex & operator=(const Mutex &) = delete;

        Mutex()
        {
            //创建并初始化锁
            int n = pthread_mutex_init(&_mutex, nullptr);
            if(n != 0)
            {
                std::cerr << "init error" << std::endl;
            }
        }
        void Lock()
        {
            //加锁
            int n = pthread_mutex_lock(&_mutex);
            if(n != 0)
            {
                std::cerr << "lock error" << std::endl;
            }
        }
        void Unlock()
        {
            //解锁
            int n = pthread_mutex_unlock(&_mutex);
            if(n != 0)
            {
                std::cerr << "unlock error" << std::endl;
            }
        }
        ~Mutex()
        {
            //销毁锁
            int n = pthread_mutex_destroy(&_mutex);
            if(n != 0)
            {
                std::cerr << "destroy error" << std::endl;
            }
        }

    private:
        pthread_mutex_t _mutex;
    };

    //RAII风格
    class MutexGuard
    {
    public:
        MutexGuard(Mutex &mutex):_mutex(mutex)
        {
            _mutex.Lock();
        }
        ~MutexGuard()
        {
            _mutex.Unlock();
        }
    private:
        Mutex &_mutex;
    };
}